Titanium.include('globals.js');
exports.createSettings = function() {

	Ti.App.Properties.setInt('IsDemo', 1);
	Ti.App.Properties.setString('Server', 'http://www.lhs.com.vn');
	Ti.App.Properties.setInt('platformWidth', Titanium.Platform.displayCaps.platformWidth);
	Ti.App.Properties.setInt('platformHeight', Titanium.Platform.displayCaps.platformHeight);
	Ti.App.Properties.setString('title', 'Thông báo');
	
	Ti.App.Properties.setInt('MainWindow_btnumber_width', 150);
	Ti.App.Properties.setInt('MainWindow_btnumber_height', 90);
	Ti.App.Properties.setInt('MainWindow_btnumber_fontsize', 38);
	Ti.App.Properties.setInt('fontsize_header', 25);
	Ti.App.Properties.setInt('TableWindow_LocationWidth', 150);
	
	
	Ti.App.Properties.setInt('button_height', 70);
	Ti.App.Properties.setInt('Order_buttonnumber_height', 50);
	Ti.App.Properties.setInt('Table_col_in',6);
	Ti.App.Properties.setInt('Table_row_in', 5);
	
	
	Ti.App.Properties.setString('borderColor', '#c0c0c0');
	Ti.App.Properties.setInt('borderRadius',0);
	Ti.App.Properties.setInt('borderWidth', 2);
	
	
	
	
	
	if(Ti.Platform.osname== 'android'){
	    Ti.App.Properties.setString('pathimage', '/Images/ipad/');
		Ti.App.Properties.setInt('MainWindow_bottom_bt', 10);
		Ti.App.Properties.setInt('MainWindow_right_bt', 10);
		Ti.App.Properties.setInt('MainWindow_space', 10);

	}
	
	else if(Ti.Platform.osname== 'ipad'){
		
	    Ti.App.Properties.setString('pathimage', '/Images/ipad/');
	    Ti.App.Properties.setInt('MainWindow_bottom_bt', 20);
		Ti.App.Properties.setInt('MainWindow_right_bt', 20);
		Ti.App.Properties.setInt('MainWindow_space', 20);
	   
	}
};
exports.ClickSound= function(){
	
	var soundFile = Ti.Media.createSound({
		url:'sound/click1.wav',
		volume : 1.0
	});
	soundFile.play();
	
}
exports.LoadedData2TableView = function(tableView,data,CreateTableViewRow,col_in) {
	
	var data_tmp1 = [];
	//Ti.API.info(data.length)
	//Ti.API.info(Math.round(data.length/col_in))
	var _row=Math.round(data.length/col_in);
	if(data.length%col_in!=0)//Khong chia het cho so cot
		_row+=1;
	
	
	var i=0;
	for (var c=0;c<_row;c++){
		var data_tmp = [];
		for (var cc=1;cc<=col_in;cc++){
			data_tmp[cc-1]=data[i]
			//Ti.API.info('AAA:'+cc+'>>>>'+data_tmp[cc].Name)
			i++;
		}
		//Ti.API.info(data_tmp)
		var row=CreateTableViewRow({
			data:data_tmp,
				
		});
		data_tmp1.push(row);
	}
	

	tableView.setData(data_tmp1);
}
exports.LoadingData2TableViewNoScrool = function(tableView,data,CreateTableViewRow) {
	var data_tmp = [];
	if(data.length==0) return
	for (var c=0;c<data.length;c++){
		var row=CreateTableViewRow({
				  data:data[c],
				  isloaded:1
			});
		data_tmp.push(row);
	}
	tableView.setData(data_tmp);
}
exports.LoadingData2TableView = function(tableView,data,CreateTableViewRow,showRows) {
	//alert(data.length)
	var data_tmp = [];
	var numberOfRows = data.length+1;
	//Ti.API.info('SL Dong'+data.length)
	//var showRows = 15;
	var rowNumer = 1;
	if(numberOfRows<showRows) showRows=numberOfRows-1
	for (var c=0;c<showRows;c++){
		//data[c] = {title:"Row "+(rowNumer)};
		
		var row=CreateTableViewRow({
				  data:data[c]
			});
		//Ti.API.info(row)
		data_tmp.push(row);
		rowNumer ++;
	}
	
	
	tableView.setData(data_tmp);
	
	
	
	var navActInd = Titanium.UI.createActivityIndicator();
	
	var updating = false;
	var loadingRow = Ti.UI.createTableViewRow({
		title:"Đang tải dữ liệu...",
		color:'#724b37',
	});
	
	function beginUpdate(){
		updating = true;
		
		navActInd.show();
	
		tableView.appendRow(loadingRow);
	
		// just mock out the reload
		setTimeout(endUpdate,2000);
	}
	
	function endUpdate(){
		updating = false;
	
		tableView.deleteRow(showRows,{});
	
		// simulate loading
		for (var c=0;c<showRows;c++)
		{
			if(rowNumer == numberOfRows){return;}
			var row=CreateTableViewRow({
				  data:data[rowNumer]
			});
			//tableView.appendRow({title:"Row "+(rowNumer)},{});
			tableView.appendRow(row,{});
			rowNumer++;
		}
		showRows = showRows * 2;
		//	numberOfRows = (numberOfRows - showRows);
	
		// just scroll down a bit to the new rows to bring them into view
	
	}
	function beginUpdate1(){
		updating = true;
		//navActInd.show();
		
		tableView.appendRow(loadingRow);
	
		// just mock out the reload
		setTimeout(endUpdate1,2000);
	}
	
	function endUpdate1(){
		updating = false;
	
		tableView.deleteRow(showRows,{});
	
		// simulate loading
		
		
		for (var c=0;c<showRows;c++){
			if(rowNumer == numberOfRows){return;}
			var row=CreateTableViewRow({
				  data:data[rowNumer]
			});
			tableView.appendRow(row,{});
			//tableView.appendRow({title:"Row "+(rowNumer)},{});
			rowNumer++;
		}
		
		
		showRows = showRows * 2;
	//	numberOfRows = (numberOfRows - showRows);
	
		// just scroll down a bit to the new rows to bring them into view
	
	}
	var lastDistance = 0; // calculate location to determine direction
	
	tableView.addEventListener('scroll',function(e){
		//Ti.API.info('SL Dong:'+numberOfRows+'DDDDD:'+rowNumer)
		//Ti.API.info('updating:'+updating)
		//if(updating==true) return;
		if (rowNumer != numberOfRows-1){
			//Ti.API.info('SL Dong:'+numberOfRows+'DDDDD:'+rowNumer)
			if(Ti.Platform.osname != 'android'){
				var offset = e.contentOffset.y;
				var height = e.size.height;
				var total = offset + height;
				var theEnd = e.contentSize.height;
				var distance = theEnd - total;
	
				// going down is the only time we dynamically load,
				// going up we can safely ignore -- note here that
				// the values will be negative so we do the opposite
				if (distance < lastDistance){
					// adjust the % of rows scrolled before we decide to start fetching
					var nearEnd = theEnd * .75;
	
					if (!updating && (total >= nearEnd))
					{
						beginUpdate();
					}
				}
				lastDistance = distance;
			}
			if(Ti.Platform.osname == 'android'){
				if((e.firstVisibleItem+e.visibleItemCount) == e.totalItemCount){
					//beginUpdate1();
					for (var c=0;c<showRows;c++){
						if(rowNumer == numberOfRows){return;}
						var row=CreateTableViewRow({
							  data:data[rowNumer]
						});
						tableView.appendRow(row,{});
						//tableView.appendRow({title:"Row "+(rowNumer)},{});
						rowNumer++;
					}
				}
			}
		}
	});
};
exports.Alert_error = function(parent,message) {
	//require('settings').createAlertDialog(Globals.title,Globals.connecterror);
		
	//Lhs.ui.activityIndicator.hideModal();
	var error = Ti.UI.createLabel({
		    textAlign:'center',	
            text:message,
            font:{
                fontSize:Ti.App.Properties.getInt('fontsize_header'),//'17dp',
            	fontWeight:'bold'
            },
            color:'#724b37',
   });
   parent.add(error)
};
	
	
exports.createAlertConnectError = function()
{
	var confirm = Titanium.UI.createAlertDialog({ 
					            title: Globals.title1, 
					            message:Globals.connecterror, 
					            buttonNames: [Globals.btOk]
					    });
	confirm.show();   
}
exports.createAlertDialog2= function(title,message,onload_function,contact_phone)
{
	var confirm = Titanium.UI.createAlertDialog({ 
					            title: title, 
					            message:message, 
					            buttonNames: [Globals.btOk,Globals.btCancel]
					    });
	 confirm.addEventListener('click', function(e) {
       //Clicked cancel, first check is for iphone, second for android
       if (e.cancel === e.index || e.cancel === true) {
          return;
       }
       switch (e.index) {
          case 0: {
          			 onload_function({contact_phone:contact_phone});
				  }
          break;
 
          //This will never be reached, if you specified cancel for index 1
          case 1: Titanium.API.info('Clicked button 1 (NO)');
          break;
 
          default:
          break;
      }
    });
	confirm.show();   
}
exports.createAlertDialog= function(title,message)
{
	var confirm = Titanium.UI.createAlertDialog({ 
					            title: title, 
					            message:message, 
					            buttonNames: [Globals.btOk]
					    });
	confirm.show();   
}



exports.checkemail= function(emailAddress)
	{
		var testresults;
		var str = emailAddress;
		var filter = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if (filter.test(str))
		{
			testresults = true;
		}
		else
		{
			testresults = false;
		}
		return (testresults);
	};


exports.loadJson= function(Jsonurl,param)
{
	  alert('json')

	var param = {        
	  "UserId" : 543769,
	  "LectureId" : 635,
	  "Price" : 2000
    };

	var xhr = Titanium.Network.createHTTPClient({
		   onload : function(e) 
		   {
		       Titanium.API.info(this.responseText);
			   json = this.responseText;
			   json=json.replace('<string xmlns="http://tempuri.org/">', '');
			   json=json.replace('<?xml version="1.0" encoding="utf-8"?>', '');
			   json=json.replace('</string>', '');
			   //alert(json)
			   return json;
			
			   //response = JSON.parse(json);
			   //alert(response.OBJECT.length);
			   //Codestrong.ui.activityIndicator.hideModal();
		   },
		   onerror : function(e) {
		      // Codestrong.ui.activityIndicator.hideModal();
		   },
		   timeout : 5000
    
	});
	xhr.open("POST",Globals.Jsonurl);
	xhr.send(param);
	return response;
};

exports.GetJson= function(Jsonurl,param,onload_even,error_even)
{
	//Codestrong.ui.activityIndicator.showModal(Globals.loading, Globals.timeout, Globals.loadingTimeout);
	var xhr = Titanium.Network.createHTTPClient({
		   onload : function(e) 
		   {
		       Titanium.API.info(this.responseText);
			   json = this.responseText;
			   json=json.replace('<string xmlns="http://tempuri.org/">', '');
			   json=json.replace('<?xml version="1.0" encoding="utf-8"?>', '');
			   json=json.replace('</string>', '');
			   json=json.replace(/(\r\n|\n|\r)/gm,"");
			   response = JSON.parse(json).OBJECT;
			   //if(response.length>0)
			   		Ti.App.fireEvent(onload_even,{datajson:response}); 
			   //Codestrong.ui.activityIndicator.hideModal();
		   },
		   onerror : function(e) {
		      Ti.App.fireEvent(error_even,{datajson:response}); 
		   },
		   timeout : 5000
    
	});
	xhr.open("POST",Jsonurl);
	xhr.send(param);
	
};
exports.GetJsonFunction= function(Jsonurl,param,onload_function,error_function)
{
	//Codestrong.ui.activityIndicator.showModal(Globals.loading, Globals.timeout, Globals.loadingTimeout);
	var xhr = Titanium.Network.createHTTPClient({
		
		   onload : function(e) 
		   {
		       Titanium.API.info('this.responseText');
			   json = this.responseText;
			   /*
			   json=json.replace('<string xmlns="http://tempuri.org/">', '');
			   json=json.replace('<?xml version="1.0" encoding="utf-8"?>', '');
			   json=json.replace('</string>', '');
			   json=json.replace(/(\r\n|\n|\r)/gm,"");
			   */
			   //response = JSON.parse(json).OBJECT;
			   alert(json);
			   //onload_function(this.responseText);
			   /*
			    onload_function({
					datajson :response,
				});
				*/
			   //Codestrong.ui.activityIndicator.hideModal();
		   },
		   onerror : function(e) {
		   		alert(e)
		   		/*
		       error_function({
				  datajson:response
			   });
			   */
		   },
		   timeout : 5000
    
	});
	xhr.open("POST",Jsonurl);
	xhr.send(param);
	
	
	
	
	
	
};


exports.GetJsonFunction_GET= function(Jsonurl,param,onload_function,error_function)
{
	//alert(Jsonurl)
	var url = Jsonurl;
	var json;
	var xhr = Ti.Network.createHTTPClient({
	    onload: function() {
	    	//json = JSON.parse(this.responseText);

	    	//Titanium.API.info(this.responseText);
	    	
    	 	onload_function({
				datajson :this.responseText,
				isconnect:1
			});
			//Lhs.ui.activityIndicator.hideModal();
			
	    },
	    onerror: function(e) {
		    error_function({
				  datajson:this.responseText
			});
	    },
	    timeout:15000
	});
	xhr.open("GET", url,true);
	
	xhr.setRequestHeader('Accept', 'application/json');
	xhr.send(param);
}






exports.downloadMultiFile = function(downloadQueue,updatevalueprocess ,callBack_DownloadOneFileFinished, callBack_DownloadMultipleFileFinished) {

	var queueIndex = 0;

	var processQueue = function(download_result) {
		//once the download of one file is finished the downloadOneFile will call back the processQueue
		//which will move the index forward and download another file
			
		if( typeof (download_result) !== 'undefined') {
			callBack_DownloadOneFileFinished(download_result);
		}
		if(queueIndex < downloadQueue.length) {


			exports.downloadOneFile(downloadQueue[queueIndex], downloadQueue[queueIndex].filepath, processQueue,updatevalueprocess);
			queueIndex++;

		} else {
			callBack_DownloadMultipleFileFinished();
		}

	};
	processQueue();
};

exports.downloadOneFile = function(downloadQueue, localFilepath, callBack_DownloadOneFileFinished,updatevalueprocess) {

	var c = Titanium.Network.createHTTPClient();
	if(null != callBack_DownloadOneFileFinished) {
		c.onerror = function(e) {
			Ti.API.info('MyApp: Download failed: url= ' + url + ' Error=' + e.error);

			callBack_DownloadOneFileFinished({
				status : e.error,
				path : '',
				index:downloadQueue.index,
				length:downloadQueue.length
			});
		};
		c.ondatastream = function(e)
		{
			//Ti.API.info('value :' + e.progress);
			updatevalueprocess({
				value : e.progress,
				VideoName:downloadQueue.item.VideoName,
				index:downloadQueue.index,
				length:downloadQueue.length
			});
					
			
		};
		c.onload = function(e) {

			if(Titanium.Platform.name === 'android') {
				// On android HTTPClient will not save the file to disk. So have to hack around it
				Ti.API.info('MyApp: (Andoid) Downloaded this file from server:.' + localFilepath);
				var f = Titanium.Filesystem.getFile(localFilepath);
				f.write(c.responseData);
			}

			callBack_DownloadOneFileFinished({
				status : c.status,
				path : localFilepath,
				item : downloadQueue.item,
				index:downloadQueue.index,
				length:downloadQueue.length
			});
		};
	}

	c.open('GET', downloadQueue.url);

	if(null != localFilepath && Titanium.Platform.name !== 'android') {
		Ti.API.info('MyApp:  (iOS) Downloaded this file from server:.' + localFilepath);
		c.file = Titanium.Filesystem.getFile(localFilepath);
	}

	c.send();
};